import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Link, routerRedux } from 'dva/router';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  message,
  Collapse,
  List,
  Radio,
  Upload,
} from 'antd';

import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import DescriptionList from 'components/DescriptionList';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';
import querystring from 'querystring';
import styles from './style.less';
import { wrapFileList } from '../../../utils/utils';
import { solo } from '../../../common/solo';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const { Description } = DescriptionList;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

const formItemLayoutOfSingleLine = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
export default class SignContractDetail extends PureComponent {
  state = {
    projectId: '',
    taskId: '',
    attachmentMap: {
      signVideo: [],
      videoSign: [],
      contract: [],
    },
    imageMap: {
      signImg: [],
    },
    loadingSign: false,
  };

  signVideoData = {
    projectId: this.state.projectId, //业务ID
    customerId: '', //客户ID
    attachType: '1', //0：图片；1：视频
    attachKind: '9480', //附件种类
    type: '签约视频', //图片类型
  };

  videoSignData = {
    projectId: this.state.projectId, //业务ID
    customerId: '', //客户ID
    attachType: '1', //0：图片；1：视频
    attachKind: '9490', //附件种类
    type: '面签视频', //图片类型
  };

  contractData = {
    projectId: this.state.projectId, //业务ID
    customerId: '', //客户ID
    attachType: '1', //0：图片；1：视频
    attachKind: '1530', //附件种类
    type: '分期合同', //图片类型
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      projectId: params.id,
      taskId: params.taskId,
    });
    (this.signVideoData.projectId = params.id),
      (this.videoSignData.projectId = params.id),
      (this.contractData.projectId = params.id),
      dispatch({
        type: 'apply/getSignContract',
        payload: {
          projectId: params.id,
        },
        callback: () => {
          const { apply: { signContractDetails } } = this.props;
          let imageMap = this.state.imageMap;
          if (signContractDetails.signImg.length > 0) {
            for (let i = 0; i < signContractDetails.signImg.length; i++) {
              imageMap.signImg.push({
                key: signContractDetails.signImg[i],
                uid: signContractDetails.signImg[i],
                name: signContractDetails.signImg[i],
                status: 'done',
                url: solo.imgShow + signContractDetails.signImg[i],
              });
            }
          }
          let attachmentMap = this.state.attachmentMap;
          if (signContractDetails.signVideo.length > 0) {
            for (let i = 0; i < signContractDetails.signVideo.length; i++) {
              attachmentMap.signVideo.push({
                key: signContractDetails.signVideo[i],
                uid: signContractDetails.signVideo[i],
                name: signContractDetails.signVideo[i],
                status: 'done',
                url: solo.fileDownload + signContractDetails.signVideo[i],
              });
            }
          }
          if (signContractDetails.videoSign.length > 0) {
            for (let i = 0; i < signContractDetails.videoSign.length; i++) {
              attachmentMap.videoSign.push({
                key: signContractDetails.videoSign[i],
                uid: signContractDetails.videoSign[i],
                name: signContractDetails.videoSign[i],
                status: 'done',
                url: solo.fileDownload + signContractDetails.videoSign[i],
              });
            }
          }
          if (signContractDetails.contract.length > 0) {
            for (let i = 0; i < signContractDetails.contract.length; i++) {
              attachmentMap.contract.push({
                key: signContractDetails.contract[i],
                uid: signContractDetails.contract[i],
                name: signContractDetails.contract[i],
                status: 'done',
                url: solo.fileDownload + signContractDetails.contract[i],
              });
            }
          }
          this.setState({
            imageMap,
            attachmentMap,
            loadingSign: true,
          });
        },
      });
  }

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '签约照片':
        this.setState({
          imageMap: { ...this.state.imageMap, signImg: fileList },
        });
        break;
    }
  };

  handleCommitSignContract = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'apply/commitSignContract',
      payload: {
        projectId: this.state.projectId,
        taskId: this.state.taskId,
      },
      callback: () => {
        const { apply: { applyResult } } = this.props;
        if (applyResult.code == 200) {
          message.success('提交成功');
          dispatch(routerRedux.push('/apply/SignContractList'));
        } else {
          message.error(applyResult.message);
        }
      },
    });
  };

  actions = [
    <Button type="primary" onClick={this.handleCommitSignContract}>
      提交
    </Button>,
    <Button>
      <Link to="/apply/SignContractList">返回</Link>
    </Button>,
  ];

  handleAttachmentUploadChange = (info, fieldName) => {
    const fileList = wrapFileList(info);
    const attachmentMap = { ...this.state.attachmentMap };
    attachmentMap[fieldName] = fileList;
    this.setState({
      attachmentMap,
    });
  };

  handleRemoveFile = fileInfo => {
    const { dispatch } = this.props;
    let key = null;
    if (fileInfo.response) {
      key = fileInfo.response.body.key;
    } else {
      key = fileInfo.key;
    }
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: key,
      },
      callback: () => {
        const { apply: { applyResult } } = this.props;
        if (applyResult.code == 200) {
          message.success('删除成功');
          dispatch({
            type: 'apply/getSignContract',
            payload: {
              projectId: this.state.projectId,
            },
          });
        } else {
          message.error(applyResult.message);
        }
      },
    });
  };

  render() {
    const { apply: { signContractDetails, applyLoading, applyPage } } = this.props;
    const { loadingSign } = this.state;

    const defaultAttachmentUploadProps = {
      name: 'file',
      action: solo.uploadImg,
      multiple: true,
      headers: {
        authorization: 'authorization-text',
      },
    };

    const videoFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.signVideo,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'signVideo');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    const videoFaceFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.videoSign,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'videoSign');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    const contractFileUploadProps = {
      ...defaultAttachmentUploadProps,
      defaultFileList: this.state.attachmentMap.contract,
      onChange: info => {
        this.handleAttachmentUploadChange(info, 'contract');
      },
      onRemove: file => {
        this.handleRemoveFile(file);
      },
    };

    return (
      <PageHeaderLayout title="签约服务">
        {/* {JSON.stringify(signContractDetails)} */}
        <Card title="业务信息" className={styles.preCheckFormCard} loading={applyLoading}>
          {/* <ApplyOrderDisplayer /> */}
          {signContractDetails && (
            <DescriptionList style={{ marginBottom: '4px' }} size="small" col="2">
              <Description term="客户名称">{signContractDetails.custName}</Description>
              <Description term="证件号">{signContractDetails.idCard}</Description>
              <Description term="家庭住址">{signContractDetails.residDetail}</Description>
              <Description term="经销商">{signContractDetails.dealerName}</Description>
              <Description term="资产种类">
                {signContractDetails.assetType == 1 ? '新车' : '二手车'}
              </Description>
              <Description term="工作地址">{signContractDetails.corpDetail}</Description>
              <Description term="所购车型">{signContractDetails.carType}</Description>
              <Description term="车价">{signContractDetails.dealerPrice}</Description>
              <Description term="分期数">{signContractDetails.loanDuration}</Description>
              <Description term="贷款金额">{signContractDetails.loanAmt}</Description>
            </DescriptionList>
          )}
        </Card>
        {loadingSign && (
          <Card
            title="签约信息"
            className={styles.preCheckFormCard}
            actions={this.actions}
            loading={applyLoading}
          >
            <Form className={styles.preCheckForm}>
              <Row>
                <Col span={12}>
                  <FormItem label="上传照片" {...formItemLayout}>
                    <ImageUploader
                      maxCount={4}
                      fieldName="签约照片"
                      label="签约照片"
                      key={1}
                      size="large"
                      showRemoveIconType={true}
                      onRemoveImage={this.handleRemoveImage}
                      // onRemoveImage={this.handleRemoveFile}
                      attachmentData={{
                        projectId: this.state.projectId, //业务ID
                        customerId: '', //客户ID
                        attachType: '0', //0：图片；1：视频
                        attachKind: '1410', //附件种类
                        type: '签约照片', //图片类型
                      }}
                      fileList={this.state.imageMap.signImg}
                      onImageUploaded={this.handleImageUploaded}
                    />
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="上传视频" {...formItemLayout}>
                    {/* <ImageUploader maxCount={1} /> */}
                    <Upload {...videoFileUploadProps} data={this.signVideoData}>
                      <Button icon="upload">上传视频</Button>
                      <div style={{ lineHeight: '40px', color: '#999999' }} />
                    </Upload>
                  </FormItem>
                </Col>
              </Row>
              {/* {JSON.stringify(this.state.attachmentMap.signVideo)} */}
              <FormItem label="视频面签" {...formItemLayoutOfSingleLine}>
                {/* <ImageUploader />
               */}
                <Upload {...videoFaceFileUploadProps} data={this.videoSignData}>
                  <Button icon="upload">上传视频</Button>
                  <div style={{ lineHeight: '40px', color: '#999999' }} />
                </Upload>
              </FormItem>

              <FormItem label="合同上传" {...formItemLayoutOfSingleLine}>
                <Upload {...contractFileUploadProps} data={this.contractData}>
                  <Button icon="upload">上传文件</Button>
                  <div style={{ lineHeight: '40px', color: '#999999' }}>
                    支持扩展名 .zip .doc .docx .pdf .jpg .png
                  </div>
                </Upload>
              </FormItem>
            </Form>
          </Card>
        )}
      </PageHeaderLayout>
    );
  }
}
